<template>
  <div class="contents">
    <el-form class="demo-form-inline" :inline="true" :model="dataFilter">
      <el-form-item label="">
        <goods-type size="mini" @selectType="changeType"></goods-type>
      </el-form-item>
      <el-form-item label="">
        <el-select
          v-model="dataFilter.is_img"
		  clearable
          class="selectW"
          placeholder="是否有商品图片"
          size="mini"
        >
          <el-option label="有商品图片" value="1" />
          <el-option label="无商品图片" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-select
          v-model="dataFilter.is_primary"
		  clearable
          class="selectW"
          placeholder="是否有详情图"
          size="mini"
        >
          <el-option label="有详情图" value="1" />
          <el-option label="无详情图" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-select
          v-model="dataFilter.state"
		  clearable
          class="selectW"
          placeholder="请选择商品状态"
          size="mini"
        >
          <el-option label="已上架" value="1" />
          <el-option label="未上架" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-input
          v-model="dataFilter.name"
		  clearable
          class="selectW"
          placeholder="请输入商品编码\名称\简称\别名\关键字"
          size="mini"
        />
      </el-form-item>
      <el-form-item>
        <el-button-group>
          <el-button size="small" @click="handleSearch">搜索</el-button>
          <el-button size="small">导出</el-button>
          <!-- <el-button size="small">导入</el-button> -->
        </el-button-group>
      </el-form-item>
    </el-form>
    <el-table :data="tableData.list" style="width: 100%;" v-loading="listLoading">
      <el-table-column label="商品" prop="name" width="180" />
      <el-table-column label="商品图" align="center" prop="goodsImagelist" width="220">
        <template slot-scope="scope">
          <span v-for="(item, index) in scope.row.goodsImagelist" :key="index">
            <el-image v-if="item.is_primary == 1" :src="item.path" style="width: 120px; height: 120px;" />
          </span>
        </template>
      </el-table-column>
      <el-table-column label="详情图" align="center" prop="goodsImagelist" width="220">
        <template slot-scope="scope">
          <span v-for="(item, index) in scope.row.goodsImagelist" :key="index">
            <el-image v-if="item.is_primary == 2" :src="item.path" style="width: 120px; height: 120px;" />
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" prop="desc" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="addGoodsImg(scope.row)">
            添加商品主图
          </el-button>
          <el-button size="mini" @click="addGoodsImg(scope.row, 'detail')">
            添加详情图片
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加商品图片弹窗 -->
    <el-dialog :modal-append-to-body="false" append-to-body :close-on-click-modal="false" custom-class="modals"
      :show-close="false" :visible.sync="mainimg" width="520px">
      <span slot="title">
        <h3>
          商品图片
          <span class="goods-title-info">
            商品主图最多只能上传1张图片，图片不大于3M
          </span>
        </h3>
      </span>
      <p>导入图片（单张图片不大于3M）</p>
      <el-upload action="https://up-z2.qiniup.com" :data="formToken" list-type="picture-card" accept=".JPG,.PNG,.JPEG"
        :on-success="uploadImg" :before-upload="beforeAvatarUpload" :limit="1" :file-list="imgList"
        :on-remove="delGoodsImg" :on-preview="handleImgPreview" :on-exceed="MoreImg">
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible" :modal-append-to-body="false" append-to-body>
        <img alt="" :src="dialogImageUrl" width="100%" />
      </el-dialog>
      <span slot="footer" class="dialog-footer">
        <el-button type="text" @click="mainimg = false">关 闭</el-button>
      </span>
    </el-dialog>
    <!-- 添加详情图片弹窗 -->
    <el-dialog :modal-append-to-body="false" append-to-body :close-on-click-modal="false" custom-class="modals"
      limit="15" :show-close="false" :visible.sync="detailimg" width="520px">
      <span slot="title">
        <h3>详情图片</h3>
      </span>
      <p>导入图片（单张图片不大于3M）最多上传25张</p>
      <el-upload action="https://up-z2.qiniup.com" :data="formToken" list-type="picture-card" accept=".JPG,.PNG,.JPEG"
        :on-success="uploadImg" :before-upload="beforeAvatarUpload" :limit="25" :file-list="imgDetailList"
        :on-remove="delGoodsImg" :on-preview="handleImgPreview">
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible" :modal-append-to-body="false" append-to-body>
        <img alt="" :src="dialogImageUrl" width="100%" />
      </el-dialog>
      <span slot="footer" class="dialog-footer">
        <el-button type="text" @click="detailimg = false">关 闭</el-button>
      </span>
    </el-dialog>
    <el-pagination background layout="total, prev, pager, next, sizes, jumper" :page-size="tableData.pageSize"
      :page-sizes="[10, 20, 30, 40]" style="text-align: right;" :total="tableData.total" @current-change="checkPage" />
  </div>
</template>

<script>
  import {
    getGoodsQueryImg,
    getGoodsAddImg,
    getGoodsDelImg,
  } from '@/api/goodsimg'
  import {
    getGoodsToken
  } from '@/api/goodslist'
  import goodsType from '@/components/goodsType.vue'
  export default {
    components: {
      goodsType,
    },
    data() {
      return {
        dataFilter: {
          category_id: '',
          is_img: '',
          is_primary: '',
          state: '',
          name: '',
          pagesize: 10,
          current: 1,
        },
        mainimg: false,
        detailimg: false,
        dialogImageUrl: '',
        dialogVisible: false,
        tableData: [],
        listLoading: true,
        domain: 'https://cdn.weikedashi.net/',
        formToken: {
          key: '',
          token: '',
        },
        Imgdata: {
          name: '',
          path: '',
          product_id: 3,
          is_primary: 1,
          remarks: '111',
          product_category: '',
          seq: 0,
          host_name: 'weikedashi',
        },
        imgList: [],
        imgDetailList: [],
      }
    },
    async created() {
      await this.getList()
    },
    methods: {
      async getList() {
        this.listLoading = true
        const res = await getGoodsQueryImg(this.dataFilter)
        this.tableData = res.data
        this.listLoading = false
      },
      changeType(data) {
        this.dataFilter.category_id = data[1]
        console.log(data)
      },
      handleSearch() {
        this.getList()
      },
      //图片超出限制
      MoreImg() {
        this.$message.warning('当前限制选择 1 个文件,需删除之前图片')
      },
      addGoodsImg(item, flag) {
        this.imgDetailList = []
        this.imgList = []
        setTimeout(() => {
          var newarr = JSON.parse(
            JSON.stringify(item.goodsImagelist).replace(/path/g, 'url')
          )
          if (flag == 'detail') {
            this.detailimg = true
            this.Imgdata.is_primary = 2
            var arr2 = []
            newarr.map((item) => {
              if (item.is_primary == 2) {
                arr2.push(item)
              }
            })
            if (this.imgDetailList.length == 0) {
              this.imgDetailList = arr2
            }
          } else {
            this.mainimg = true
            this.Imgdata.is_primary = 1
            var arr1 = []
            newarr.map((item) => {
              if (item.is_primary == 1) {
                arr1.push(item)
              }
            })
            if (this.imgList.length == 0) {
              this.imgList = arr1
            }
          }
          this.Imgdata.product_id = item.id
          this.Imgdata.product_category = item.category_id
        }, 1000)
      },
      generate_key() {
        var timestamp = new Date().getTime()
        var str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
        var arr = str.split('')
        var result = ''
        for (var i = 0; i < 8; i++) {
          var n = Math.floor(Math.random() * arr.length)
          result += arr[n]
        }
        this.formToken.key = result + timestamp
      },
      async beforeAvatarUpload(file) {
        if (file.size / 1024 / 1024 > 3) {
          this.$message({
            message: '上传文件大小不能超过 3MB!',
            type: 'error'
          })
          return false
        }
        const res = await getGoodsToken()
        this.formToken.token = res.data.token
        this.generate_key()
      },
      async uploadImg(res, file) {
        const imgurl = this.domain + res.key
        this.Imgdata.path = imgurl
        this.Imgdata.name = file.name
        const ret = await getGoodsAddImg(this.Imgdata)
        // this.detailimg = false
        this.mainimg = false
        if (ret.status == '200') {
          this.$notify({
            message: '图片添加成功',
            type: 'success',
          })
          this.getList()
        }
      },
      handleImgPreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      async delGoodsImg(file) {
        const res = await getGoodsDelImg({
          id: file.id,
        })
        if (res.status == '200') {
          this.$notify({
            message: '图片删除成功',
            type: 'success',
          })
          this.getList()
        }
      },
      checkPage(page) {
        this.dataFilter.current = page
        this.getList()
      },
    },
  }
</script>

<style lang="scss" scoped>
  .contents {
    padding: 5px 15px;

    .selectW {
      width: 150px;
    }

    .goods-title-info {
      margin-left: 10px;
      font-size: 14px;
      color: #80848f;
    }
  }
</style>
